#!/usr/bin/env python
"""
##############################################################################
用法：./searchall.py dir string [-l(list only)]
搜索指定的目录及其子目录下所有含有指定字符串的文件；首先利用os.walk接口而不是find.find来收
集文件名；类似于find.find('*')的每个返回结果调用visitfile。
##############################################################################
"""

import os
import sys

LISTONLY = False
TEXTEXTS = ['.py', '.pyw', '.txt', '.c', '.cpp', '.h']


def searcher(startdir, searchkey, listonly=LISTONLY):
    global fcount, vcount
    fcount = vcount = 0

    for thisdir, subsdir, files in os.walk(startdir):
        for fn in files:
            fp = os.path.join(thisdir, fn)
            visitfile(fp, searchkey, listonly)


def visitfile(fpath, searchkey, listonly=LISTONLY, textexts=TEXTEXTS):
    global fcount, vcount
    print(vcount + 1, '->', fpath)

    try:
        if not listonly:
            if os.path.splitext(fpath)[1] not in textexts:
                print('跳过：', fpath)
            elif searchkey in open(fpath).read():
                input('{} 中有字符串 {}'.format(fpath, searchkey))
                fcount += 1
    except Exception:
        print('失败：', fpath, sys.exc_info()[0], sys.exc_info()[1])

    vcount += 1


def command(listonly=LISTONLY):
    searcher(sys.argv[1], sys.argv[2], '-l' in sys.argv)
    print('访问了', vcount, '个文件，匹配了', fcount, '个。')


if __name__ == '__main__':
    command()
